package com.hhd.flow.controller;

import cn.hutool.core.io.IoUtil;
import com.hhd.flow.engine.FlowEngine;
import com.hhd.flow.engine.support.ClassPathResource;
import com.hhd.flow.engine.support.DefaultFlowResource;
import com.hhd.flow.engine.support.FlowResource;
import com.hhd.flow.engine.utils.CommonUtils;
import com.hhd.flow.engine.vo.FlowUser;
import com.hhd.flow.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@RestController
@RequestMapping("/flow/user")
public class FlowUserController {
    @Autowired
    FlowEngine flowEngine;

    @GetMapping("/avatar")
    public void getById(String id, HttpServletResponse response) {
        FlowUser flowUser = flowEngine.getFlowUserById(id);
        FlowResource resource = null;

        if (!CommonUtils.isEmpty(flowUser)) resource = flowUser.getAvatar();
        else resource = getDefaultAvatarResource();

        try (InputStream is = resource.getInputStream()) {
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(is, outputStream);
            return;
        } catch (Exception e) {
        }

        resource = getDefaultAvatarResource();
        try (InputStream is = resource.getInputStream()) {
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(is, outputStream);
        } catch (Exception e) {
        }
    }

    private FlowResource getDefaultAvatarResource() {
        DefaultFlowResource resource = new DefaultFlowResource();
        resource.setName("default");
        resource.setInputStream(new ClassPathResource("avatar", "/avatar/defaut.png").getInputStream());
        return resource;
    }


    @GetMapping("/getUserSign")
    public void getUserSign(String userSign, HttpServletResponse response) {
        FlowResource flowResource = flowEngine.loadUserSign(userSign);
        if (CommonUtils.isEmpty(flowResource)) return;
        try (InputStream inputStream = flowResource.getInputStream()) {
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(inputStream, outputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/getCurrentUserSign")
    public Result getCurrentUserSign() {
//        String userSign = flowEngine.getCurrentUserSign();
        String userSign = "";
        Result<Object> result = Result.ok();
        result.setResult(userSign);
        return result;
    }
}
